<template>
  <div class="wrap">
    <div class="wrap-button">
      <a-button v-show="!isManager" style="margin-right: 8px" type="primary" @click="showModal"
        >新增</a-button
      >
      <a-button v-show="isManager" style="margin-right: 8px" type="primary" @click="handleExport"
        >批量发货</a-button
      >
      <!-- <a-button v-show="isManager" style="margin-right: 8px" type="primary">导出全部</a-button> -->
      <div style="float: right">
        <a-radio-group
          v-model:value="recordSo.orderStatus"
          button-style="solid"
          style="margin-right: 8px"
          @change="reload"
        >
          <a-radio-button value="">全部</a-radio-button>
          <a-radio-button value="0" v-if="!isManager">已保存</a-radio-button>
          <a-radio-button value="1">未发货</a-radio-button>
          <a-radio-button value="3">已发货</a-radio-button>
          <a-radio-button value="4">已签收</a-radio-button>
        </a-radio-group>

        <a-select
          v-if="isManager"
          v-model:value="recordSo.orderUserId"
          style="width: 120px; margin-right: 8px"
          placeholder="下单人姓名"
          allowClear
          @change="reload"
        >
          <a-select-option v-for="item in allUserList" :key="item.userId" :value="item.userId">{{
            item.realName
          }}</a-select-option>
        </a-select>
        <a-input
          v-model:value="recordSo.consigneeName"
          style="width: 140px; margin-right: 8px"
          placeholder="收件人姓名"
          allow-clear
          @pressEnter="reload"
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input>
        <a-input
          v-model:value="recordSo.consigneeTel"
          style="width: 140px; margin-right: 8px"
          placeholder="收件人电话"
          allow-clear
          @pressEnter="reload"
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input>
        <a-input
          v-model:value="recordSo.consigneeAddress"
          style="width: 140px; margin-right: 8px"
          placeholder="收件人地址"
          allow-clear
          @pressEnter="reload"
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input>
        <a-input
          v-model:value="recordSo.orderCode"
          style="width: 140px; margin-right: 8px"
          placeholder="订单编号查询"
          allow-clear
          @pressEnter="reload"
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input>
        <a-input
          v-model:value="recordSo.productName"
          style="width: 140px; margin-right: 8px"
          placeholder="产品名称查询"
          allow-clear
          @pressEnter="reload"
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input>
        <!-- <a-input
          v-model:value="recordSo.trackCode"
          style="width: 140px; margin-right: 8px"
          placeholder="物流单号查询"
          allow-clear
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input> -->
        <a-range-picker
          style="margin-right: 8px; width: 240px"
          v-model:value="orderTimeRange"
          valueFormat="YYYY-MM-DD"
          @panelChange="reload"
        />
        <a-button type="primary" @click="list">查询</a-button>
      </div>
    </div>
    <div class="wrap-table">
      <!-- <BaseTitle title="用户列表" /> -->
      <a-table
        :loading="loading"
        :dataSource="data"
        :columns="columns"
        size="middle"
        @change="handleTableChange"
        width="300"
        :pagination="pagination"
        :custom-row="customRow"
        :row-selection="isManager ? rowSelection : null"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'orderCode'">
            <a-popover style="width: 500px" title="订单详情" trigger="hover">
              <template #content>
                <a-table :columns="checkColumns" :data-source="record.products" size="small" />
              </template>
              {{ record.orderCode }}
            </a-popover>
          </template>
          <template v-if="column.key === 'afloatStatus'">
            <a-tag color="#f50" v-if="record.afloatStatus === 1">途</a-tag>
            <div v-else></div>
          </template>
          <template v-if="column.key === 'operation'">
            <a-button
              v-if="!isManager && (record.orderStatus == 0 || record.orderStatus == 1)"
              :disabled="!(record.orderStatus == 0 || record.orderStatus == 1)"
              class="button-interval"
              type="link"
              size="small"
              @click="handleEdit(record)"
            >
              修改
            </a-button>
            <a-button
              v-if="!isManager && (record.orderStatus == 0 || record.orderStatus == 1)"
              class="button-interval"
              type="link"
              size="small"
              @click="handleCancel(record)"
              :disabled="!(record.orderStatus == 0 || record.orderStatus == 1)"
            >
              撤单
            </a-button>
            <!-- <a-button
              v-if="isManager && record.orderStatus == 0"
              class="button-interval"
              type="link"
              size="small"
              @click="handleLock(record)"
            >
              锁单
            </a-button>
            <a-button
              v-if="isManager && record.orderStatus == 1"
              class="button-interval"
              type="link"
              size="small"
              @click="handleUnLock(record)"
            >
              取消锁单
            </a-button> -->
            <a-button
              v-if="isManager && record.orderStatus == 1"
              class="button-interval"
              type="link"
              size="small"
              @click="handleDeliver(record)"
              :disabled="!(record.orderStatus == 1)"
            >
              发货
            </a-button>
            <a-button
              v-if="isManager && record.orderStatus == 3"
              class="button-interval"
              type="link"
              size="small"
              @click="handleUnDeliver(record)"
              :disabled="!(record.orderStatus == 3)"
            >
              取消发货
            </a-button>
          </template>
          <template v-if="column.key === 'orderStatus'">
            <a-tag v-if="record.orderStatus == 0" color="processing">已保存</a-tag>
            <a-tag v-else-if="record.orderStatus == 1" color="orange">未发货</a-tag>
            <a-tag v-else-if="record.orderStatus == 3" color="green">已发货</a-tag>
            <a-tag v-else-if="record.orderStatus == 4" color="green">已签收</a-tag>
            <a-tag v-else-if="record.orderStatus == 9" color="red">已撤单</a-tag>
            <a-tag v-else color="red">未知</a-tag>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal
      v-model:visible="open"
      :title="createMode ? '创建订单' : '修改订单'"
      width="1100px"
      :bodyStyle="{ padding: '16px 24px 0px 24px' }"
      :centered="false"
    >
      <template #footer>
        <a-button key="save" type="primary" :loading="submitLoading" @click="handleSubmit(true)"
          >保存订单</a-button
        >
        <a-button key="submit" type="primary" :loading="submitLoading" @click="handleSubmit(false)"
          >提交订单</a-button
        >
      </template>
      <div>
        <a-form
          ref="formRef"
          :model="orderBo"
          name="basic"
          autocomplete="off"
          @finish="handleCreate"
        >
          <a-form-item>
            <a-checkbox v-model:checked="defaultSender">使用默认寄件人</a-checkbox>
          </a-form-item>
          <a-row :gutter="8">
            <a-col class="gutter-row" :span="5">
              <a-form-item
                label="收件人"
                name="consigneeName"
                :rules="[{ required: true, message: '请输入收件人姓名' }]"
              >
                <a-input v-model:value="orderBo.consigneeName" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="6">
              <a-form-item
                label="手机号"
                name="consigneeTel"
                :rules="[{ required: true, message: '请输入收件人手机号' }]"
              >
                <a-input v-model:value="orderBo.consigneeTel" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="13">
              <a-form-item
                label="收件人地址"
                name="consigneeAddress"
                :rules="[{ required: true, message: '请输入收件人地址' }]"
              >
                <a-input v-model:value="orderBo.consigneeAddress" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="8" v-if="!defaultSender">
            <a-col class="gutter-row" :span="5">
              <a-form-item
                label="寄件人"
                name="senderName"
                :rules="[{ required: true, message: '请输入寄件人姓名' }]"
              >
                <a-input v-model:value="orderBo.senderName" :disabled="defaultSender" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="6">
              <a-form-item
                label="手机号"
                name="senderTel"
                :rules="[{ required: true, message: '请输入寄件人手机号' }]"
              >
                <a-input v-model:value="orderBo.senderTel" :disabled="defaultSender" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="13">
              <a-form-item
                label="寄件人地址"
                name="senderAddress"
                :rules="[{ required: true, message: '请输入寄件人地址' }]"
              >
                <a-input v-model:value="orderBo.senderAddress" :disabled="defaultSender" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="备注" name="remark">
            <a-input v-model:value="orderBo.remark" />
          </a-form-item>

          <StoreProduct @add-product="addCheckProduct" :key="randomKey" ref="child" />

          <CheckProduct :data="checkProduct" @cancelProduct="cancelProduct" />

          <!-- <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
            <a-button type="primary" html-type="submit">Submit</a-button>
          </a-form-item> -->
        </a-form>
      </div>
    </a-modal>
    <a-modal
      v-model:visible="detailVisible"
      title="订单明细"
      :width="1020"
      :bodyStyle="{ padding: '16px 24px 0px 24px' }"
      style="padding: 0px 24px"
      @ok="detailVisible = false"
      :footer="null"
    >
      <a-descriptions
        bordered
        size="small"
        :labelStyle="{ minWidth: '80px' }"
        :contentStyle="{ minWidth: '120px' }"
      >
        <a-descriptions-item label="收件人">{{ orderBo.consigneeName }}</a-descriptions-item>
        <a-descriptions-item label="手机号">{{ orderBo.consigneeTel }}</a-descriptions-item>
        <a-descriptions-item label="地址">{{ orderBo.consigneeAddress }}</a-descriptions-item>
        <a-descriptions-item label="寄件人">{{ orderBo.senderName }}</a-descriptions-item>
        <a-descriptions-item label="手机号">{{ orderBo.senderTel }}</a-descriptions-item>
        <a-descriptions-item label="地址">{{ orderBo.senderAddress }}</a-descriptions-item>
        <a-descriptions-item label="备注">{{ orderBo.remark }}</a-descriptions-item>
      </a-descriptions>
      <a-table :columns="checkColumns" :data-source="checkProduct" size="small" />
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, reactive, onMounted, nextTick, unref } from 'vue'
  import {
    pageOrder,
    createOrder,
    updateOrder,
    cancelOrder,
    lockOrder,
    deliverOrder,
    unLockOrder,
    unDeliverOrder,
    listAllCreateOrderId,
    exportCheckedOrder,
  } from '/@/api/order'
  import { OrderVO, OrderSO, OrderBO } from '/@/api/order/model/orderModel'
  import { ProductSimpleVO } from '/@/api/product/model/productModel'
  import { listAllUser, addUser, deleteUser, listUserRole, saveUserRole } from '/@/api/sys/user'
  import { ListAllUserModel, FormState } from '/@/api/sys/model/userModel'
  import StoreProduct from './components/StoreProduct.vue'
  import CheckProduct from './components/CheckProduct.vue'
  import type { FormInstance } from 'ant-design-vue'
  import { SearchOutlined } from '@ant-design/icons-vue'
  import { message, Modal, Table } from 'ant-design-vue'
  import { useUserStore } from '/@/store/modules/user'
  import type { Dayjs } from 'dayjs'
  type RangeValue = [string, string]
  const orderTimeRange = ref<RangeValue>()
  const loading = ref(false)
  const open = ref<boolean>(false)
  const defaultSender = ref<boolean>(true)
  const oneselfDeliver = ref<boolean>(false)
  const submitLoading = ref<boolean>(false)
  const detailVisible = ref<boolean>(false)
  const force = ref<boolean>(false)

  const formRef = ref<FormInstance>()
  const child = ref()
  const userStore = useUserStore()
  const isManager = userStore.getManager
  const isAdmin = userStore.getAdmin
  const getUserInfo = userStore.getUserInfo
  const createMode = ref<boolean>(true)
  const randomKey = ref<string>('')
  let orderBo = reactive<OrderBO>({
    id: undefined,
    senderName: '刘昊然',
    senderTel: '15888888888',
    senderAddress: '浙江省嘉兴市秀洲区阳光小区',
    consigneeName: undefined,
    consigneeTel: undefined,
    consigneeAddress: undefined,
    remark: undefined,
    products: [],
    saveFlag: false,
    afloatStatus: 0,
    force: false,
  })
  const customRow = (record: OrderBO) => {
    return {
      onDblclick: () => {
        checkProduct.value = record.products

        orderBo.senderName = record.senderName
        orderBo.senderTel = record.senderTel
        orderBo.senderAddress = record.senderAddress
        orderBo.consigneeName = record.consigneeName
        orderBo.consigneeTel = record.consigneeTel
        orderBo.consigneeAddress = record.consigneeAddress
        orderBo.remark = record.remark
        detailVisible.value = true
      },
    }
  }

  const columns = [
    {
      title: '订单编码',
      dataIndex: 'orderCode',
      key: 'orderCode',
      align: 'center',
    },
    {
      title: '下单人',
      dataIndex: 'orderUserName',
      key: 'orderUserName',
      align: 'center',
      width: 120,
    },
    {
      title: '寄件人',
      dataIndex: 'senderName',
      key: 'senderName',
      align: 'center',
      width: 120,
    },
    {
      title: '收件人',
      dataIndex: 'consigneeName',
      key: 'consigneeName',
      align: 'center',
      width: 120,
    },
    {
      title: '收件人手机',
      dataIndex: 'consigneeTel',
      key: 'consigneeTel',
      align: 'center',
      width: 160,
    },
    {
      title: '收件人地址',
      dataIndex: 'consigneeAddress',
      key: 'consigneeAddress',
      align: 'center',
      width: 200,
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      align: 'center',
      width: 100,
    },
    {
      title: '在途订单',
      dataIndex: 'afloatStatus',
      key: 'afloatStatus',
      align: 'center',
      width: 100,
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 160,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      align: 'center',
      width: 160,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      align: 'center',
      width: 200,
    },
  ]

  const checkColumns = [
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      align: 'center',
    },
    {
      title: '有效期',
      dataIndex: 'limitTime',
      key: 'limitTime',
      align: 'center',
      width: 100,
    },
    {
      title: '购买数量',
      dataIndex: 'quantity',
      key: 'quantity',
      align: 'center',
      width: 100,
    },
  ]

  const selectedRowKeys = ref<OrderVO['id'][]>([])
  const allSelectedRowKeys = ref<OrderVO['id'][]>([])
  let keySet: Set<string> = new Set<string>()
  const selectAll = ref<boolean>(false)
  let keyArray: string[] = []
  const onSelectChange = (changableRowKeys: string[]) => {
    console.log('selectedRowKeys changed: ', changableRowKeys)
    selectedRowKeys.value = changableRowKeys
  }
  const rowSelection = computed(() => {
    return {
      selectedRowKeys: unref(allSelectedRowKeys),
      onChange: onSelectChange,
      hideDefaultSelections: false,
      onSelectAll: (selected, selectedRows, changeRows) => {
        //selected 点击全选是否选中
        //selectedRows 点击全选判断所有的选中数据
        //changeRows 所有改变选中状态的数据
        console.log('全选了', selected)
        if (selected) {
          if (selectAll.value) {
            selectAll.value = false
            allSelectedRowKeys.value = []
          } else {
            selectAll.value = true
            keySet.clear()
            listAllCreateOrderId()
              .then((res) => {
                console.log('res', res)
                res.forEach((element) => {
                  keySet.add(element)
                })
              })
              .then(() => {
                allSelectedRowKeys.value = []
                keySet.forEach((e) => {
                  console.log('key set item', e)
                  allSelectedRowKeys.value.push(e)
                })
              })
          }
        } else {
          keySet.clear()
          allSelectedRowKeys.value = []
        }
      },
      onSelect: (record, selected, selectedRows, nativeEvent) => {
        //record 点击某一条的所有数据
        //selected 点击的一条是否被选中
        console.log('当前点的id', record)
        console.log('当前点的selected', selected)
        if (selected) {
          if (record.orderStatus == 3) {
            message.error('当前订单已发货，不允许勾选')
            return
          }
          if (record.orderStatus == 4) {
            message.error('当前订单已签收，不允许勾选')
            return
          }
          if (record.orderStatus == 9) {
            message.error('当前订单已撤销，不允许勾选')
            return
          }
          allSelectedRowKeys.value.push(record.id)
        } else {
          allSelectedRowKeys.value.splice(allSelectedRowKeys.value.indexOf(record.id), 1)
        }
      },
    }
  })

  let checkProduct = ref<ProductSimpleVO[]>([])
  let allUserList = ref<ListAllUserModel[]>([])

  let data = ref<OrderVO[]>([])
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 15,
    size: '',
    showSizeChanger: false,
    showQuickJumper: false,
  })
  const pageParam = computed(() => ({
    query: recordSo,
    current: pagination.value?.current,
    size: pagination.value?.pageSize,
  }))
  let recordSo = reactive<OrderSO>({
    orderUserId: isManager ? undefined : getUserInfo.userId.toString(),
    consigneeName: undefined,
    consigneeTel: undefined,
    consigneeAddress: undefined,
    orderCode: undefined,
    trackCode: undefined,
    orderStatus: '',
    afloatStatus: 0,
    orderTimeStart: undefined,
    orderTimeEnd: undefined,
    productName: undefined,
  })

  onMounted(() => {
    list()
    listAllUserFunc()
    console.log('isManager', isManager)
  })

  async function list() {
    loading.value = true
    pageParam.value.query.orderTimeStart = orderTimeRange.value?.[0]
    pageParam.value.query.orderTimeEnd = orderTimeRange.value?.[1]
    const res = await pageOrder(pageParam.value)
    data.value = res.records
    pagination.value.total = Number(res.total)
    pagination.value.current = Number(res.current)
    loading.value = false
  }

  function handleTableChange(page) {
    pagination.value.current = page.current
    list()
  }

  const showModal = () => {
    createMode.value = true
    checkProduct.value = []
    child.value?.setCurrentPage(1)
    child.value?.list()

    open.value = true
    nextTick(() => {
      formRef.value?.resetFields()
      defaultSender.value = true
      orderBo.consigneeName = undefined
      orderBo.consigneeTel = undefined
      orderBo.consigneeAddress = undefined
      orderBo.senderName = '刘昊然'
      orderBo.senderTel = '15888888888'
      orderBo.senderAddress = '浙江省嘉兴市秀洲区阳光小区'
      orderBo.remark = undefined
      orderBo.products = []
      orderBo.afloatStatus = 0
      orderBo.force = false
    })
  }

  function handleCreate() {
    open.value = false
  }

  const reload = () => {
    pagination.value.current = 1
    list()
  }

  const addCheckProduct = (item) => {
    let _item = JSON.parse(JSON.stringify(item))
    _item.productId = item.id
    console.log('item', item)
    console.log('checkProduct', checkProduct.value)
    const checkIndex = checkProduct.value.findIndex((p) => p.productId === item.id)
    if (checkIndex > -1) {
      if (checkProduct.value[checkIndex].quantity >= checkProduct.value[checkIndex].storeNum) {
        message.error('库存不足')
      } else {
        checkProduct.value[checkIndex].quantity += 1
        message.success('加购成功')
      }
    } else {
      if (item.storeNum === 0) {
        message.error('库存不足')
      } else {
        _item.quantity = 1
        checkProduct.value.push(_item)
        message.success('加购成功')
      }
    }
  }

  const cancelProduct = (item) => {
    checkProduct.value.splice(
      checkProduct.value.findIndex((p) => p.productId === item.productId),
      1,
    )
  }
  const handleSubmit = async (saveFlag: boolean) => {
    submitLoading.value = true
    try {
      await formRef.value?.validateFields()
      if (checkProduct.value?.length === 0) {
        message.error('请选择商品')
        submitLoading.value = false
        return
      } else {
        console.log('checkProduct', checkProduct.value)
        orderBo.afloatStatus = 0
        orderBo.products = checkProduct.value.map((p) => {
          if (p.afloatStatus == 1) {
            orderBo.afloatStatus = 1
          }
          let product = {
            productId: p.productId,
            productName: p.productName,
            quantity: p.quantity,
          }
          return product
        })
        orderBo.saveFlag = saveFlag
        if (orderBo.afloatStatus == 1) {
          Modal.confirm({
            title: '提示',
            content: '该订单包含在途产品，将自动转为保存订单',
            onOk() {
              console.log('OK')
              orderBo.saveFlag = true
              if (createMode.value) {
                createOrder(orderBo)
                  .then((res) => {
                    console.log('createOrder', res)
                    if (res) {
                      open.value = false
                      message.success('下单成功')
                      list()
                    } else {
                      message.error('下单失败')
                    }
                  })
                  .catch((error) => {
                    console.log('err', error.message)
                    if (error.message === '订单重复') {
                      Modal.confirm({
                        title: '提示',
                        content: '订单重复，请确认是否依然要下单',
                        onOk() {
                          orderBo.force = true
                          handleSubmit(orderBo.saveFlag)
                        },
                        // eslint-disable-next-line @typescript-eslint/no-empty-function
                        onCancel() {},
                      })
                    }
                  })
                  .finally(() => {
                    submitLoading.value = false
                  })
              } else {
                updateOrder(orderBo)
                  .then((res) => {
                    console.log('createOrder', res)
                    if (res) {
                      open.value = false
                      message.success('修改成功')
                      list()
                    } else {
                      message.error('修改失败')
                    }
                  })
                  .catch((error) => {
                    console.log('err', error.message)
                    if (error.message === '订单重复') {
                      Modal.confirm({
                        title: '提示',
                        content: '订单重复，请确认是否依然要下单',
                        onOk() {
                          orderBo.force = true
                          handleSubmit(orderBo.saveFlag)
                        },
                        // eslint-disable-next-line @typescript-eslint/no-empty-function
                        onCancel() {},
                      })
                    }
                  })
                  .finally(() => {
                    submitLoading.value = false
                  })
              }
            },
            onCancel() {
              submitLoading.value = false
              return
            },
          })
        } else {
          if (createMode.value) {
            createOrder(orderBo)
              .then((res) => {
                console.log('createOrder', res)
                if (res) {
                  open.value = false
                  message.success('下单成功')
                  list()
                } else {
                  message.error('下单失败')
                }
              })
              .catch((error) => {
                console.log('err', error.message)
                if (error.message === '订单重复') {
                  Modal.confirm({
                    title: '提示',
                    content: '订单重复，请确认是否依然要下单',
                    onOk() {
                      orderBo.force = true
                      handleSubmit(orderBo.saveFlag)
                    },
                    // eslint-disable-next-line @typescript-eslint/no-empty-function
                    onCancel() {},
                  })
                }
              })
              .finally(() => {
                submitLoading.value = false
              })
          } else {
            updateOrder(orderBo)
              .then((res) => {
                console.log('createOrder', res)
                if (res) {
                  open.value = false
                  message.success('修改成功')
                  list()
                } else {
                  message.error('修改失败')
                }
              })
              .catch((error) => {
                console.log('err', error.message)
                if (error.message === '订单重复') {
                  Modal.confirm({
                    title: '提示',
                    content: '订单重复，请确认是否依然要下单',
                    onOk() {
                      orderBo.force = true
                      handleSubmit(orderBo.saveFlag)
                    },
                    // eslint-disable-next-line @typescript-eslint/no-empty-function
                    onCancel() {},
                  })
                }
              })
              .finally(() => {
                submitLoading.value = false
              })
          }
        }
      }
    } catch (errorInfo) {
      submitLoading.value = false
      message.error('提交失败，请检查表单项')
      console.log('Failed:', errorInfo)
    }
  }
  const handleEdit = async (record) => {
    console.log('record', record)
    child.value?.setCurrentPage(1)
    child.value?.list()
    createMode.value = false
    orderBo.id = record.id
    orderBo.consigneeName = record.consigneeName
    orderBo.consigneeTel = record.consigneeTel
    orderBo.consigneeAddress = record.consigneeAddress
    orderBo.senderName = record.senderName
    orderBo.senderTel = record.senderTel
    orderBo.senderAddress = record.senderAddress
    orderBo.remark = record.remark
    orderBo.force = false
    checkProduct.value = record.products
    if (record.senderName == '刘昊然') {
      defaultSender.value = true
    } else {
      defaultSender.value = false
    }
    open.value = true
  }
  const handleCancel = (record) => {
    cancelOrder(record.id).then((res) => {
      if (res) {
        message.success('订单取消成功')
        pageParam.value.current = 1
        list()
      } else {
        message.error('订单取消失败')
      }
    })
  }

  const handleLock = (record) => {
    lockOrder(record.id).then((res) => {
      if (res) {
        message.success('锁单成功')
        pageParam.value.current = 1
        list()
      } else {
        message.error('锁单失败')
      }
    })
  }
  const handleUnLock = (record) => {
    unLockOrder(record.id).then((res) => {
      if (res) {
        message.success('取消锁单成功')
        pageParam.value.current = 1
        list()
      } else {
        message.error('取消锁单失败')
      }
    })
  }
  const handleDeliver = (record) => {
    deliverOrder(record.id).then((res) => {
      if (res) {
        message.success('发货成功')
        pageParam.value.current = 1
        list()
      } else {
        message.error('发货失败')
      }
    })
  }
  const handleUnDeliver = (record) => {
    unDeliverOrder(record.id).then((res) => {
      if (res) {
        message.success('取消发货成功')
        pageParam.value.current = 1
        list()
      } else {
        message.error('取消发货失败')
      }
    })
  }

  const changeOneselfDeliver = (e) => {
    console.log('changeOneselfDeliver', e)
    if (e.target.checked) {
      console.log('checked')
    } else {
      console.log('unchecked')
    }
  }
  const test = () => {
    Modal.confirm({
      title: 'Do you want to delete these items?',
      icon: '',
      content: 'When clicked the OK button, this dialog will be closed after 1 second',
      onOk() {
        return new Promise((resolve, reject) => {
          setTimeout(Math.random() > 0.5 ? resolve : reject, 1000)
        }).catch(() => console.log('Oops errors!'))
      },
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      onCancel() {
        Modal.destroyAll()
      },
    })
  }
  import axios from 'axios'
  const listAllUserFunc = () => {
    listAllUser().then((res) => {
      allUserList.value = res
    })
  }

  const handleExport = () => {
    let shouldUpdate = false
    if (allSelectedRowKeys.value.length == 0) {
      message.error('请先选择导出数据')
      return
    }
    Modal.confirm({
      title: '提示',
      content: '是否同步更新订单状态为【已发货】？',
      onOk() {
        console.log('OK')
        shouldUpdate = true
        handleExportCheckedOrder(true).then(() => {
          reload()
        })
      },
      onCancel() {
        console.log('Cancel')
        handleExportCheckedOrder(false).then(() => {
          reload()
        })
      },

      class: 'test',
    })
  }
  const handleExportCheckedOrder = async (shouldUpdate: boolean) => {
    exportCheckedOrder(allSelectedRowKeys.value, shouldUpdate).then((export_data) => {
      let link = document.createElement('a')
      let blogw = new Blob([export_data], { type: 'application/vnd.ms-excel;charset=utf-8' })
      let objectUrl = window.URL.createObjectURL(blogw)
      link.href = objectUrl
      let file_name = `面单信息.xlsx`
      link.download = file_name
      link.click()
      window.URL.revokeObjectURL(objectUrl)
    })
  }
</script>
<style lang="scss" scoped>
  .wrap {
    &-table {
      margin-top: 16px;
    }
  }
</style>
